package org.android.pasos;

import static java.text.DateFormat.SHORT;

import java.text.DateFormat;
import java.util.List;
import java.util.Locale;

import org.android.pasos.util.UtilJSON;
import org.android.pasos.util.UtilTrama;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.view.accessibility.AccessibilityManager;
import android.widget.ListView;

public class WalkMainActivity extends ListActivity implements OnInitListener {
	/** Called when the activity is first created. */
	protected Criteria criteria;
	protected LocationManager locationManager;
	protected DateFormat dateFormat = java.text.DateFormat.getDateInstance(
			SHORT, Locale.ENGLISH);
	private SharedPreferences pref;
	Context context;
	private Vibrator vibrator;
	// private Hablar voz;
	private TextToSpeech tts;
	private AccessibilityManager accessibilityManager;
	private static final int NOTIF_ALERTA_ID = 1;
	private SharedPreferences mPrefs;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.walk_main);

		pref = PreferenceManager
				.getDefaultSharedPreferences(WalkMainActivity.this);
		

		mPrefs = getSharedPreferences("PasosPreferences", MODE_PRIVATE);

		Context ctx = getApplicationContext();
		Resources res = ctx.getResources();

		// voz = new Hablar();
		tts = new TextToSpeech(this, this);
		accessibilityManager = (AccessibilityManager) ctx
				.getSystemService(Context.ACCESSIBILITY_SERVICE);

		String[] options = res.getStringArray(R.array.title_names_walk);
		TypedArray icons = res.obtainTypedArray(R.array.pasos_icons_walk);

		setListAdapter(new ImageAndTextAdapter(ctx, R.layout.main_list_item,
				options, icons));
	}

	public void onListItemClick(ListView parent, View v, int position, long id) {
		Intent intent = null;

		// Show position clicked
		/**
		 * Toast.makeText(getApplicationContext(), "You have selected " +
		 * (position + 1) + "th item", Toast.LENGTH_SHORT).show();
		 */

		switch (position) {
		case 0:
			hablar(this.getString(R.string.tts_iniciar_paseo));
			// Option --> START WALK TIME
			vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(50);

			location(position);
			controlDistance();

			break;
		case 1:
			hablar(this.getString(R.string.tts_posicion_actual));
			// Option --> POSITION
			vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(50);

			location(position);
			controlDistance();
			break;
		case 2:
			hablar(this.getString(R.string.tts_volver_casa));
			// Option --> COMEBACK HOME
			vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(50);

			location(position);
			break;
		case 3:
			hablar(this.getString(R.string.tts_atras));
			// Option --> RETURN MENU
			vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(50);

			intent = new Intent(WalkMainActivity.this, MainActivity.class);
			startActivity(intent);
			break;
		}

	}

	private void location(int position) {
		// initialize
		context = getApplicationContext();
		locationManager = (LocationManager) getApplicationContext()
				.getSystemService(Context.LOCATION_SERVICE);
		// Coarse accuracy is specified here to get the fastest possible result.
		// The calling Activity will likely (or have already) request ongoing
		// updates using the Fine location provider.
		criteria = new Criteria();
		criteria.setAccuracy(Criteria.ACCURACY_COARSE);

		if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
			createGpsDisabledAlert();
			Log.d("", "sadfasdfasdfasdfasdf");
		} else {

			locationManager = (LocationManager) context
					.getSystemService(Context.LOCATION_SERVICE);
			List<String> matchingProviders = locationManager.getAllProviders();

			for (String provider : matchingProviders) {
				locationManager.removeUpdates(singeUpdateListener);
				Location location = locationManager
						.getLastKnownLocation(provider);

				if (position == 1) {
					showPosition(location);
				} else if (position == 2) {
					showWay(location);
				}

				// Se le pide a cada proveedor que intente obtener la posicion
				// actual
				locationManager.requestLocationUpdates(provider, 0, 0,
						singeUpdateListener, context.getMainLooper());
			}
		}

	}

	private void createGpsDisabledAlert() {

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(this.getString(R.string.gps_desc))
				.setCancelable(false)
				.setPositiveButton(this.getString(R.string.gps_activar),
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								showGpsOptions();
							}
						});
		builder.setNegativeButton(this.getString(R.string.nada),
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});

		AlertDialog alert = builder.create();
		alert.show();

	}

	private void showGpsOptions() {
		Intent gpsOptionsIntent = new Intent(
				android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
		startActivity(gpsOptionsIntent);
	}

	protected LocationListener singeUpdateListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			locationManager.removeUpdates(singeUpdateListener);
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}

		public void onProviderEnabled(String provider) {
		}

		public void onProviderDisabled(String provider) {
		}
	};

	// Muestra localizacion actual en el mapa
	public void showPosition(Location location) {
		if (location != null) {

			Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
					Uri.parse("geo:" + location.getLatitude() + ","
							+ location.getLongitude()));

			startActivity(intent);

		}

	}

	// Muestra el camino de la posicion actual hasta la direccion dada.
	public void showWay(Location location) {
		if (location != null) {

			String direccion = mPrefs.getString("Pdireccion", "defValue");
			direccion = direccion.replace(' ', '+');
			Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr="
					+ location.getLatitude() + "," + location.getLongitude()
					+ "&daddr=" + "?q=" + direccion + "&hl=en");
			Intent it = new Intent(android.content.Intent.ACTION_VIEW, uri);
			startActivity(it);
		}

	}

	protected LocationListener controlUpdateListener = new LocationListener() {
		public void onLocationChanged(Location location) {
			// Se envia la peticion REST al servidor
			DatosTrama dt = UtilTrama.creartrama(getApplicationContext());
			UtilJSON.enviarIncidencia(getApplicationContext(), Constants.URL_INCIDENCIAS_REST,
					Constants.ALEJAMIENTO, dt);
			// Obtenemos una referencia al servicio de notificaciones
			String ns = Context.NOTIFICATION_SERVICE;
			NotificationManager notManager = (NotificationManager) getSystemService(ns);

			// Configuramos la notificaci�n
			int icono = android.R.drawable.stat_sys_warning;
			CharSequence textoEstado = getString(R.string.alerta);
			long hora = System.currentTimeMillis();

			Notification notif = new Notification(icono, textoEstado, hora);

			// Configuramos el Intent
			Context contexto = getApplicationContext();
			CharSequence titulo = getString(R.string.msg_alerta);
			CharSequence descripcion = getString(R.string.fuera_perim);

			Intent notIntent = new Intent(contexto, WalkMainActivity.class);

			PendingIntent contIntent = PendingIntent.getActivity(contexto, 0,
					notIntent, 0);

			notif.setLatestEventInfo(contexto, titulo, descripcion, contIntent);

			// AutoCancel: cuando se pulsa la notificaion esta desaparece
			notif.flags |= Notification.FLAG_AUTO_CANCEL;

			// A�adir sonido, vibracion y luces
			notif.defaults |= Notification.DEFAULT_SOUND;
			// notif.defaults |= Notification.DEFAULT_VIBRATE;
			long[] vibrate = { 0, 1000, 200, 3000, 200, 3000 };
			notif.vibrate = vibrate;
			notif.defaults |= Notification.DEFAULT_LIGHTS;

			// Enviar notificacion
			notManager.notify(NOTIF_ALERTA_ID, notif);
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
		}

		public void onProviderEnabled(String provider) {
		}

		public void onProviderDisabled(String provider) {
		}
	};

	public void controlDistance() {
		locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER,
				30000, 10, controlUpdateListener, context.getMainLooper());
	}

		private void hablar(String mensaje) {
			if (accessibilityManager.isEnabled()) {
			tts.speak(mensaje, TextToSpeech.QUEUE_FLUSH, null);
		}
	}

	public void onInit(int status) {
	}
}
